package com.sw.rpc.handler;

import com.sw.rpc.bootstrap.SpringApplication;
import com.sw.rpc.service.IUserService;
import com.sw.rpc.service.RpcRequest;
import com.sw.rpc.service.zk.ServiceInstanceService;
import com.sw.rpc.service.zk.ZkNodeData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.zookeeper.data.Stat;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.time.Duration;
import java.time.Instant;

/**
 * @author sw
 * @project zdy-rpc
 * @description
 * @date 2020/5/15 13:33
 */
public class UserServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("收到消息了吗？");
        // 定义开始时间
        Instant startInsant = Instant.now();
        String rpcRequest=(String) msg;
        IUserService userServicce= (IUserService) SpringApplication.beanConaoners.get("userServiceImpl");
        String result = userServicce.sayHello(rpcRequest);
        ctx.writeAndFlush(result);
        //定义结束时间
        Instant endInstant = Instant.now();
        //计算处理时长
        long seconds = Duration.between(startInsant, endInstant).getSeconds();

        //更新数据信息
        InetSocketAddress remoteAddress = (InetSocketAddress) ctx.pipeline().channel().remoteAddress();
        InetSocketAddress socketAddress = (InetSocketAddress) ctx.pipeline().channel().localAddress();
        System.out.println(socketAddress.getHostName()+":"+socketAddress.getPort());
        /***
         * 模拟机器响应停顿时间
         */
        if(socketAddress.getPort()==8081){
            Thread.sleep(4000L);
        }
        ZkNodeData zkNodeData=new ZkNodeData();
        zkNodeData.setIp(socketAddress.getHostName());
        zkNodeData.setPort(socketAddress.getPort());
        zkNodeData.setLastResponseTime(Instant.now());
        zkNodeData.setHandlerTime(seconds);
        Long zxid=ServiceInstanceService.updateZKNoData(socketAddress.getHostName()+":"+socketAddress.getPort(),zkNodeData);
        System.out.println("更新数据事务id："+zxid);

    }
}
